<?php

namespace app\admin\command;

use think\console\Command;
use think\console\Input;
use think\console\input\Option;
use think\console\Output;
use think\Db;
use think\Exception;
use think\Log;
use app\common\library\Faceid as FaceIdLib;
use app\admin\model\pt\Person as PersonModel;

class CheckDetect extends Command
{
    protected function configure()
    {
        $this->setName('check_detect')
            ->setDescription('calc user credit');
    }

    protected function execute(Input $input, Output $output)
    {
        @ini_set("memory_limit", '-1');
        $stime = microtime(true);
        $curTime = time();
        $faceidLib = new FaceIdLib();
        // 查找待获取结果的
        $persons = PersonModel::where('biz_token', '<>', '')
          ->where('confirm_idcard', '0')->select();
        foreach ($persons as $personModel) {
            // 认证结束时间已到的
            if ($personModel->confirm_end_time <= $curTime) {
                $checkRes = $faceidLib->getDetectInfo($personModel->biz_token);
                $msg = $checkRes['msg'];
                $data = $checkRes['data'];
                
                if ($msg != 'ok') {
                    Log::write('check dectct error : ' . $msg . ", data" . var_export($data, true));
                    continue;
                }
                $textRes = $data['Text'];
                if ($textRes['Comparemsg'] == '成功') {
                    // 判断是否与提交的姓名和身份证号一致
                    if ($textRes['IdCard'] != $personModel->id_card || $textRes['Name'] != $personModel->user_name) {
                        $personModel->confirm_idcard = 2;
                        $personModel->confirm_desc = '第三方活体认证结果与输入的姓名或身份证不一致';
                        $msg = '失败';
                    } else {
                        $personModel->confirm_idcard = 1;
                        $personModel->confirm_desc = '认证成功';
                        $personModel->confirm_time = time();
                        $msg = '成功';
                    }
                } else {
                    $personModel->confirm_idcard = 2;
                    $personModel->confirm_desc = $textRes['ErrMsg'];
                    $msg = '失败';
                }
                $personModel->confirm_end_time = 0;
                $personModel->save();
            }
        }

        $etime = microtime(true);//获取程序执行结束的时间
        $total = $etime - $stime;   //计算差值
        $output->writeln($total);
    }

}
